<template>
  <view class="build-group">
    <view class="f">
      <view class="top">
        <span class="back" @click='back'>
          <span class="back">取消</span>
        </span>
        <span class="title">创建群聊</span>
      </view>
    </view>

    <view class="main">
      <view class="tops">
        <!-- 群头像 -->
        <view class="group-img">
          <image :src="info.groupImgurl" mode="" @click="updatedPic"></image>
          <div v-if="info.isShowPic">
            <qf-image-cropper :width="500" :height="500" :radius="30" @crop="handleCrop"></qf-image-cropper>
          </div>
        </view>
        <!-- 群名字 -->
        <view class="group-name">
          <uni-easyinput class="uni-mt-5" v-model="info.groupname" trim="all" placeholder="为群取个名字吧~"></uni-easyinput>
        </view>
        <view class="title">用户</view>
      </view>

      <view class="friends">
        <view class="user" v-for='(item,index) in info.friendlist' :key="index" @click="selectFriend(item)">
          <view class="selected" :class="{isselected:item.selected}">
            <image src="../../static/images/group/choose.png" class="selected-img" v-if="item.selected" mode=""></image>
          </view>
          <image class="user-img" :src="item.imgurl" mode=""></image>
          <view class="name" v-if="item.nickname != null">{{item.nickname}} </view>
          <view class="name" v-else>{{item.username}} </view>
        </view>
      </view>
    </view>

    <view class="btn">
      <view class="bottom-btn">
        <button @click="submit" type='default' :disabled="selectedNum == 0 || info.groupname.trim() == ''">创建群聊
          <span v-show="selectedNum !=0">({{selectedNum}})</span></button>
      </view>
    </view>
  </view>
</template>

<script setup>
  import {
    reactive,
    getCurrentInstance,
    computed
  } from 'vue'
  import {
    useUserStore
  } from '@/store/user.js'
  import {
    useGroupStore
  } from '@/store/group.js'
  import {
    onLoad,
  } from '@dcloudio/uni-app'
  import {
    requestNet
  } from '@/api/base.js'
  const user = useUserStore()
  const group = useGroupStore()
  const instance = getCurrentInstance()

  let info = reactive({
    isShowPic: false, //是否显示裁剪图片插件
    groupImgurl: '../../static/images/group/group.png', //群头像
    groupimgurl: '', //最终群头像
    seletctedUser: [], //已选择好友id数组
    groupname: '', //群名
    friendlist: [], //好友列表
  })
  const userInfo = reactive({
    myid: null, //登录用户id
    token: ''
  })
  //统计选择人数
  let selectedNum = computed({
    set(value) {},
    get() {
      let num = 0
      for (let i = 0; i < info.friendlist.length; i++) {
        if (info.friendlist[i].selected) {
          num++
        }
      }
      return num
    }
  })

  //获取当前用户缓存信息
  function getNowUserInfo() {
    userInfo.myid = user.userinfo.userid
    userInfo.token = user.token
  }

  function back() {
    uni.navigateTo({
      url: '/pages/home/home'
    })
  }

  //更新群头像
  function updatedPic() {
    info.isShowPic = true
  }

  //裁剪图片  点击确认之后
  function handleCrop(e) {
    info.groupImgurl = e.tempFilePath
    //上传图片
    uni.uploadFile({
      url: `${instance.proxy.serverUrl}/files/upload`, //仅为示例，非真实的接口地址[后端接口地址]
      filePath: e.tempFilePath,
      name: 'file',
      fileType: 'image',
      formData: {
        url: 'group',
        name: new Date().getTime().toString() + userInfo.myid
      },
      header: {
        token: userInfo.token
      },
      success: (uploadFileRes) => {
        console.log(uploadFileRes)
        //获取后端返回的
        info.groupimgurl = uploadFileRes.data
      }
    });
    uni.previewImage({
      urls: [e.tempFilePath],
      current: 0
    });
    info.isShowPic = false
  }

  //获取好友用户数据
  function getFriendList() {
    requestNet({
      url: '/home/getUserList',
      data: {
        uid: userInfo.myid,
        state: 0
      },
      header: {
        token: userInfo.token
      }
    }).then(res => {
      let code = res.data.code
      if (code == 200) {
        info.friendlist = res.data.data
        let temp = info.friendlist
        if (temp.length > 0) {
          for (let i = 0; i < temp.length; i++) {
            temp[i].selected = false
            if (!temp[i].imgurl.includes(instance.proxy.serverUrl)) { //不包含服务器地址
              info.friendlist[i].imgurl = `${instance.proxy.serverUrl}${temp[i].imgurl}`
            }
          }
        }
      }
    }).catch(err => {
      uni.showToast({
        title: err,
        icon: 'error'
      })
    })
  }

  //创建群聊
  function submit() {
    for (let i = 0; i < info.friendlist.length; i++) {
      if (info.friendlist[i].selected) {
        info.seletctedUser.push(info.friendlist[i].id)
      }
    }
    //最后添加群主id
    info.seletctedUser.push(userInfo.myid)
    requestNet({
      url: '/group/creategroup',
      method: 'POST',
      data: {
        groupname: info.groupname,
        imgurl: info.groupimgurl,
        user: info.seletctedUser
      },
      header: {
        token: userInfo.token
      }
    }).then(res => {
      console.log(res)
      let code = res.data.code
      if (code == 200) {
        uni.showToast({
          title: '创建成功',
          icon: 'success'
        })
      }
      //清空选择框
      info.groupname = ''
      info.seletctedUser = []
      //跳转到首页
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/home/home'
        })
      }, 2000)
    }).catch(err => {
      uni.showToast({
        title: err,
        icon: 'error'
      })
    })
  }

  //动态选择好友
  function selectFriend(item) {
    item.selected = !item.selected
  }

  onLoad((e) => {
    getNowUserInfo()
    getFriendList()
  })
</script>

<style lang="scss" scoped>
  @import '@/assets/css/main.scss';

  .build-group {
    padding: 0 20rpx;

    .f {
      width: 95%;
      position: fixed;
      z-index: 100;
    }

    .top {
      position: relative;
      display: flex;
      align-items: center;
      height: 88rpx;
      border-bottom: 2rpx solid var(--text-color-grey);
      background-color: $uni-bg-color-grey;

      .back {
        display: inline-block;
        height: 60rpx;
        width: 60rpx;
        line-height: 60rpx;
        font-weight: 700;
      }

      .title {
        position: absolute;
        //居中显示
        transform: translateX(-50%);
        left: 50%;
        font-size: 36rpx;
        font-weight: 700;
      }
    }

    .main {
      display: flex;
      flex-direction: column;

      .tops {
        padding-top: 90rpx;
        position: fixed;
        background-color: #fff;
        z-index: 10;
        width: 95%;

        .group-img {
          margin: 10px auto;
          width: 196rpx;
          height: 196rpx;
          background-color: #f0d32e;
          border-radius: 40rpx;
          box-shadow: 0px 36rpx 40rpx 0px rgba(39, 40, 50, 0.2);
          position: relative;

          image {
            position: absolute;
            height: 150rpx;
            width: 150rpx;
            border-radius: 10px;
            transform: translateX(-50%);
            left: 50%;
            top: 12%;
          }
        }

        .group-name {
          margin: 40rpx 60rpx 0 60rpx;
        }

        .title {
          padding: 20rpx 40rpx;
          font-size: 44rpx;
          font-weight: 600;
          line-height: 40px;
        }
      }

      .friends {
        padding: 550rpx 40rpx 120rpx 40rpx;

        .user {
          display: flex;
          flex-direction: row;
          align-items: center;
          height: 120rpx;

          .selected {
            flex: none;
            margin-right: 30rpx;
            width: 48rpx;
            height: 48rpx;
            background: #f0f072;
            border-radius: 24rpx;
            position: relative;

            &-img {
              width: 30rpx;
              height: 20rpx;
              position: absolute;
              left: 10rpx;
              top: 15rpx;
            }
          }

          .user-img {
            flex: none;
            width: 80rpx;
            height: 80rpx;
          }

          .name {
            margin-left: 30rpx;
            font-size: 32rpx;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            overflow: hidden;
          }
        }

      }
    }
  }

  .btn {
    box-shadow: 0px 1px 0 rgba(0, 0, 0, .25);
    margin: 0 20rpx;

    .bottom-btn {
      position: fixed;
      bottom: 30rpx;
      width: 90%;
    }
  }

  .isselected {
    background: rgba(255, 228, 49, 1) !important;
  }

  :deep(.is-input-border[data-v-abe12412]) {
    border-color: #e1e1e1 !important;
    border-radius: 46px;
    text-align: center;
  }

  :deep(.content-clear-icon[data-v-abe12412]) {
    color: rgb(192, 196, 204) !important;
  }

  .image-cropper[data-v-6592bb66] {
    z-index: 1;
  }

  uni-button[type='default'] {
    border-radius: 20px;
    background-color: #f0d32e;
  }

  .noselect {
    background: #d9d9d9 !important;
  }
</style>
